#include "main.h"

App::App() {
    window = new RenderWindow(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), WINDOW_TITLE);
    
    // Reduce CPU usage
    window->SetFramerateLimit(FRAMERATE_LIMIT);
    
    currentState = new MainMenuState(window);
}

int App::start() {        
    while (window->IsOpened()) {
        if (currentState->stateId != currentState->nextState) {
            changeState(currentState->nextState);
        }

        // Process events
        currentState->onHold();
        
        Event event;
        while (window->GetEvent(event)) {
            currentState->onEvent(event);
        }

        currentState->render();
    }

    return EXIT_SUCCESS;
}

void App::changeState(PossibleState nextState) {
    State* oldState = currentState;

    switch (nextState) {
        case MAIN_MENU:
            currentState = new MainMenuState(window);
            break;
            
        // TODO: create state classes
        case OPTIONS:
            currentState = new LevelSelectState(window);
            break;
            
        case CREDITS:
            currentState = new LevelSelectState(window);
            break;
            
        case LEVEL_SELECT:
            currentState = new LevelSelectState(window);
            break;
            
        case START_GAME:
            currentState = new LevelSelectState(window);
            break;

        case LEVEL:
            // Can only getSelectedLevel() from MainMenuState
            currentState = new LevelState(window, ((LevelSelectState*)oldState)->getSelectedLevel());
            break;
            
        case QUIT:
            window->Close();
            break;
    }

    delete oldState;
}

App::~App() {
    delete window;
    delete currentState;
}

int main() {
    // Set current directory to find resources
    chdir(RESOURCE_DIRECTORY);
    
    // Initialize globals
    sysDoc.LoadFile();
    sysXml = sysDoc.RootElement();
    
    // TODO: vvv for instructional purposes only
//    long* result = (long*)callPython("hello.py", "myFunc");
//    cout << *result << endl;

    App hellmaco;
    return hellmaco.start();
}
